import { Request, Response } from 'express';
import mongoose from 'mongoose';
import { z } from 'zod';

import { ProjectModel } from '../../models/project';
import { sendErrorResponse, sendSuccessResponse } from '../../utils/response';

/**
 * 删除项目脚本组的路径参数验证模式
 */
export const deleteProjectScriptParamsSchema = z.object({
  id: z.string().regex(/^[0-9a-fA-F]{24}$/, '项目ID格式不正确'),
  title: z.string().min(1, '脚本组标题不能为空').max(100, '脚本组标题不能超过100个字符'),
});

export type DeleteProjectScriptParams = z.infer<typeof deleteProjectScriptParamsSchema>;

/**
 * 删除项目脚本组
 * @description 删除指定项目的指定脚本组（从 scripts 数组中删除 title 匹配项）
 * @route DELETE /api/project/script-group/:id/:title
 * @param req Express请求对象
 * @param res Express响应对象
 * @returns Promise<Response> 删除结果响应
 *
 * @example
 * DELETE /api/project/script-group/507f1f77bcf86cd799439011/分组A
 *
 * 成功响应:
 * {
 *   "success": true,
 *   "code": 200,
 *   "message": "脚本组删除成功",
 *   "data": {
 *     "project": {
 *       "_id": "507f1f77bcf86cd799439011",
 *       "name": "示例项目",
 *       "scripts": [ ... ]
 *     },
 *     "deletedScriptsCount": 3
 *   }
 * }
 */
export async function deleteProjectScript(req: Request, res: Response): Promise<Response> {
  const session = await mongoose.startSession();

  try {
    const { id, title } = req.params as DeleteProjectScriptParams;

    await session.startTransaction();

    // 查询项目及脚本组
    const project = await ProjectModel.findById(id).session(session);
    if (!project) {
      await session.abortTransaction();
      return sendErrorResponse(res, 404, '项目不存在');
    }
    if (!Array.isArray(project.scripts)) {
      await session.abortTransaction();
      return sendErrorResponse(res, 400, '项目脚本组数据结构异常');
    }
    // 查找目标脚本组
    const groupIndex = project.scripts.findIndex((g: any) => g.title === title);
    if (groupIndex === -1) {
      await session.abortTransaction();
      return sendErrorResponse(res, 404, '未找到指定脚本组');
    }
    const deletedScriptsCount = Array.isArray(project.scripts[groupIndex].scripts)
      ? project.scripts[groupIndex].scripts.length
      : 0;
    // 删除该脚本组
    project.scripts.splice(groupIndex, 1);
    await project.save({ session });
    await session.commitTransaction();
    const responseData = {
      deletedScriptsCount,
      project,
    };
    return sendSuccessResponse(res, responseData, '脚本组删除成功');
  } catch (error) {
    await session.abortTransaction();
    console.error('删除项目脚本组失败:', error);
    if (error instanceof Error) {
      switch (error.name) {
        case 'CastError':
          return sendErrorResponse(res, 400, '项目ID格式不正确');
        case 'MongoServerError':
          return sendErrorResponse(res, 500, '数据库操作失败');
        default:
          return sendErrorResponse(res, 500, '服务器内部错误');
      }
    }
    return sendErrorResponse(res, 500, '服务器内部错误');
  } finally {
    await session.endSession();
  }
}
